"""登录接口"""

from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from flask_jwt_extended import (
    get_jwt_identity,
    jwt_required,
    create_access_token,
)
from common.res import res, ValidationArgs, RESCODE
from common.tokens_jwt import generate_token
from models.user import UserModel


class Login(Resource):
    """登录"""

    def post(self):
        parser = RequestParser(ValidationArgs)
        parser.add_argument("user_name", type=str, required=True, trim=True)
        parser.add_argument("pwd", type=str, required=True, trim=True)
        parser.add_argument("keep", type=bool, required=False)

        data = parser.parse_args()
        print(f"params {data}")
        user_name = data["user_name"]
        pwd = data["pwd"]
        keep = data["keep"] or False

        try:
            user = UserModel.query.filter_by(user_name=user_name).first()
        except Exception as e:
            print(f"login_err {e}")
            return res(code=RESCODE.DB_FAIL)

        if not user or not user.check_password(pwd):
            return res(code=RESCODE.LOGIN_FAIL, message="用户名或密码错误")

        return res(data=generate_token(user_name, keep))


class RefreshToken(Resource):
    """刷新token"""

    @jwt_required(refresh=True)
    def post(self):
        current_user = get_jwt_identity()
        access_token = create_access_token(identity=current_user)
        # TODO 旧的token加入黑名单
        data = {"accessToken": access_token}
        return res(data=data)


class Protected(Resource):
    """测试token"""

    @jwt_required()
    def post(self):
        user_name = get_jwt_identity()
        print(f"user_name{user_name}")
        return res()
